import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '../stores/modules/user'
import { getDeviceType, getTargetPort } from '@/utils/deviceDetector';

// 定义路由关系

//移动端 创建路由器
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL), // 简化参数
  routes: [
    {
      path: '/login',
      name: 'Login',
      component: () => import('@/views/login/index.vue'), // 登录页
      meta: { title: '登录页' }, // 设置页面中文名
    },

    {
      path: '/',
      name: 'Layout',
      component: () => import('@/views/layout/index.vue'), // 布局容器
      meta: { title: '毕业生之家(✿◠‿◠)~-GradLink' }, // 设置页面中文名
      redirect: '/home',
      children: [
        {
          path: '/home',
          name: 'Home',
          component: () => import('@/views/layout/Home.vue'), // 首页  对应pc端的首页'/'
          meta: { title: '毕业生之家(✿◠‿◠)~-GradLink' }
        },
        {
          path: '/moments',
          name: 'Moments',
          component: () => import('@/views/layout/Moments.vue'), // 动态  对应pc端的动态页'/moments'
          meta: { title: '动态' }
        },
        {
          
          path: '/activity',
          name: 'Activity',
          component: () => import('@/views/layout/Activity.vue'), // 发布活动  对应pc端的发布活动页'/activity-manage',但不需要子路由
          meta: { title: '发表活动' },
         
        },
        {
          path: '/user',
          name: 'User',
          component: () => import('@/views/layout/User.vue'), // 我的  ,重新设计我的页面,含我的报名,我的消息等等
          meta: { title: '我的' }
        }
      ]
    },


    {
      path: '/moment/publish',  // 使用单数形式，与详情页保持一致
      name: 'PublishMoment',
      component: () => import('@/views/moments/PublishMoment.vue')
    },
    {
      path: '/moment/:momentId/comment/:commentId',
      name: 'CommentDetail',
      component: () => import('@/views/moments/CommentDetail.vue')
    },
    {
      path: '/moment/:momentId',
      name: 'MomentDetail',
      component: () => import('@/views/moments/MomentDetail.vue')
    },
    /**
           * 
           * 功能描述	对应路径	组件文件
活动主页（发表活动入口）	/activity	@/views/layout/Activity.vue
草稿列表	/activity/drafts	@/views/activity/DraftList.vue
已发表活动列表	/activity/published	@/views/activity/PublishedList.vue
富文本编辑页（第一步）	/activity/edit/:eventId?	@/views/activity/ActivityEditor.vue
封面及信息编辑页（第二步）	/activity/edit/:eventId/preview	@/views/activity/ActivityPreview.vue
活动详情页	/alumni-event/:eventId	@/views/article/AlumniEventDetail.vue
           */

    
    // 活动相关
    {
      path: '/activity/drafts',
      name: 'DraftList',
      component: () => import('@/views/activity/DraftList.vue')
    },
    {
      path: '/activity/published',
      name: 'PublishedList',
      component: () => import('@/views/activity/PublishedList.vue')
    },
    {
      path: '/activity/edit/:eventId?',
      name: 'ActivityEditor',
      component: () => import('@/views/activity/ActivityEditor.vue'),
      children: [
        {
          path: 'preview',
          component: () => import('@/views/activity/ActivityPreview.vue')
        }
      ]
    },

    // 搜索页
    {
      path: '/searchList',
      name: 'SearchList',
      component: () => import('@/views/search/SearchList.vue'),
      meta: { title: '搜索' }
    },
    // 文章详情
    {
      path: '/career-resource/:resourceId',
      name: 'CareerResourceDetail',
      component: () => import('@/views/articles/CareerResourceDetail.vue')
    },
    {
      path: '/alumni-event/:eventId',
      name: 'AlumniEventDetail',
      component: () => import('@/views/articles/AlumniEventDetail.vue')
    },

    // 个人中心相关
    {
      path: '/user-center/my-registrations',
      name: 'MyRegistrations',
      component: () => import('@/views/user/MyRegistrations.vue')
    },
    {
      path: '/user-center/profile',
      name: 'UserProfile',
      component: () => import('@/views/user/UserProfile.vue')
    },
    {
      path: '/user-center/settings',
      name: 'UserSettings',
      component: () => import('@/views/user/UserSettings.vue')
    },
    {
      path: '/403',
      name: 'Forbidden',
      component: () => import('../views/error/403.vue'),
      meta: { title: '无权限访问' }
    }
    // 其他路由可以继续添加在这里
  ]
})



// 登录访问拦截 => 默认是直接放行的
// 根据返回值决定，是放行还是拦截
// 返回值：
// 1. undefined / true 直接放行
// 2. false 拦回 from 的地址页面
// 3. 具体路径或路径对象拦截到对应的地址






import { convertPath } from '../../../routeMap'
const whiteList = ['/login', '/403'] // 白名单路径

router.beforeEach(async (to) => {

  const currentPort = window.location.port
  const targetPort = getTargetPort()
  const deviceType = getDeviceType()


  // if (currentPort !== targetPort) {
  //   // 保留协议、主机名和路径，仅替换端口
  //   const newUrl = `${window.location.protocol}//${window.location.hostname}:${targetPort}${to.path}`
  //   window.location.replace(newUrl)
  //   return
  // }
  if (currentPort !== targetPort) {
    const convertedPath = convertPath(to.path, deviceType)
    const newUrl = `${window.location.protocol}//${window.location.hostname}:${targetPort}${convertedPath}`
    window.location.replace(newUrl)
    return
  }

  // 权限检查
  const userStore = useUserStore()
  const hasToken = userStore.token

  // 1. 白名单直接放行
  if (whiteList.includes(to.path)) return true

  // 2. 无token情况处理
  if (!hasToken) {
    return `/login?redirect=${encodeURIComponent(to.fullPath)}`
  }

  // 3. 有token时需要检查用户信息
  if (!userStore.user?.userId) {
    try {
      await userStore.getUser() // 获取用户信息
    } catch (e) {
      userStore.clearUser()
      return '/login'
    }
  }

  // 4. 角色权限检查（核心逻辑）
  const userRole = userStore.user?.userRole?.code
  // console.log('userRole', userRole);
  const requiredRoles = to.meta.roles // 从路由meta获取所需角色
  //1是管理员,2是学生,3是老师
  if (requiredRoles) {
    // 就业数据分析页需要admin或teacher角色
    if (requiredRoles.includes('admin') || requiredRoles.includes('teacher')) {
      if (userRole !== 1 && userRole !== 3) { // 既不是admin也不是teacher
        return '/403' // 无权限页面
      }
    }
  }

  return true;
});

// 后置路由守卫
router.afterEach((to) => {
  // 获取 meta 中的 title
  const title = to.meta.title
  if (title) {
    // 设置页面标签
    document.title = title
  } else {
    // 如果没有设置 title，使用默认标题
    document.title = '毕业生之家(✿◠‿◠)~-GradLink'
  }
})
//导出路由
export default router
